package com.example.demo.service.iml;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.DeviceConfigMapper;
import com.example.demo.model.entity.DeviceConfig;
import com.example.demo.service.DeviceConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class DeviceConfigServiceImpl extends ServiceImpl<DeviceConfigMapper, DeviceConfig>
        implements DeviceConfigService {

    @Override
    public DeviceConfig getByImei(String imei) {
        return baseMapper.selectOne(new QueryWrapper<DeviceConfig>()
                .eq("imei", imei)
                .last("LIMIT 1"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateConfig(DeviceConfig config, String openid) {
        DeviceConfig existing = getByImei(config.getImei());
        if (existing != null) {
            config.setId(existing.getId());
            config.setOpenid(openid);
            return updateById(config);
        }
        config.setOpenid(openid);
        return save(config);
    }
}
